package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.FocusUser;
import com.itheima.domain.mongo.RecommendVideo;
import com.itheima.domain.mongo.Video;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.domain.vo.VideoVo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.FocusUserService;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Component
public class VideoManager {

    @DubboReference
    private VideoService videoService;

    @DubboReference
    private UserInfoService userInfoService;
    //小视频的列表
    @Cacheable(value = "tanhua" , key = "'video_'+#userId + '_' + #page +'_'+#pagesize")
    public PageBeanVo smallVideos(Long userId , Integer page, Integer pagesize) {
        System.out.println("读取视频列表");
        //1.获得用户的id
        //userId = UserHolder.getUserId();
        //2.查询推荐的视频
        PageBeanVo pageBeanVo = videoService.findRecommendVideoByPage(userId, page, pagesize);
        //3.拿到推荐的集合数据
        List<Video> videoList = (List<Video>) pageBeanVo.getItems();
        List<VideoVo> videoVoList = new ArrayList<>();
        //4.遍历
        if(CollectionUtil.isNotEmpty(videoList)){
            for (Video video : videoList) {
                //4.2 查询用户数据
                UserInfo userInfo = userInfoService.findByUserId(video.getUserId());
                //4.3 封装vo
                VideoVo vo = new VideoVo();
                //两个对象都有id属性  先封装数据的会被后封装数据的id覆盖
                vo.setUserInfo( userInfo ); //赋值用户数据
                //有先后顺序  先封装用户数据 再封装 视频数据  为什么?
                vo.setVideo( video ); //赋值小视频数据

                //判断是否关注过
                String key = StrUtil.format(ConstantUtil.FOCUS_USER , UserHolder.getUserId() , video.getUserId() );
                if(stringRedisTemplate.hasKey(key)){
                    vo.setHasFocus(1);//是关注过
                }

                videoVoList.add(vo);
            }
        }

        //5.封装分页对象
        pageBeanVo.setItems(videoVoList);
        return pageBeanVo;
    }

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired //java的客户端  报错不管 编译报错
    private FastFileStorageClient client;

    @Autowired //nginx服务器
    private FdfsWebServer server;
    //保存视频
    @CacheEvict(value = "tanhua" ,allEntries = true)
    public ResponseEntity saveVideo(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //1.获得用户id
        Long loginUserId = UserHolder.getUserId();
        //2.上传图片 - 保存oss平台
        String imagePath = null;
        if(videoThumbnail!=null && videoThumbnail.getSize()>0){
            imagePath = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        }
        
        //3.上传视频 - 保存到 fastDFS
        String filePath = null;
        if(videoFile!=null && videoFile.getSize()>0){
            InputStream is = videoFile.getInputStream(); //文件流
            long size = videoFile.getSize(); //文件大小
            String extName = FileUtil.extName(videoFile.getOriginalFilename()); //文件后缀
            StorePath storePath = client.uploadFile(is, size, extName, null);//存储的对象
            filePath= server.getWebServerUrl() + storePath.getFullPath();//拼接文件上传的路径
        }
        //4.构建video
        Video video = new Video();
        video.setCreated(System.currentTimeMillis());//时间
        video.setUserId(loginUserId);  //发布人id
        video.setText("左手右手一个慢动作!!!");//视频标题
        video.setPicUrl(imagePath);//封面路径
        video.setVideoUrl(filePath); //视频路径

        //5.保存video
        videoService.publishVideo(video);
        return ResponseEntity.ok(null);
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @DubboReference
    private FocusUserService focusUserService;
    //关注
    public ResponseEntity userFocus(Long focusUserId) {
        FocusUser focusUser = new FocusUser();
        focusUser.setUserId( UserHolder.getUserId());//我
        focusUser.setFocusUserId( focusUserId ); //关注的小视频坐着
        //关注
        focusUserService.save(focusUser);
        //格式化key
        String key = StrUtil.format(ConstantUtil.FOCUS_USER , UserHolder.getUserId() , focusUserId );
        //放入缓存  没有设置时间
        stringRedisTemplate.opsForValue().set(  key , "1");
        return ResponseEntity.ok(null);
    }
    //取消关注
    public ResponseEntity userUnFocus(Long focusUserId) {
        //取消关注
        focusUserService.remove(UserHolder.getUserId() , focusUserId);
        //删除缓存
        String key = StrUtil.format(ConstantUtil.FOCUS_USER , UserHolder.getUserId() , focusUserId );
        stringRedisTemplate.delete(key);
        return ResponseEntity.ok(null);
    }
}
